# import os
# import sys
# import click
import datetime
from datetime import date
from collections import OrderedDict

from flask import Flask,render_template,request,Response,redirect,url_for,flash,jsonify
import config
from extension import db
from model import Equipment,Module
from menus.menuutils import get_function_menu

from faker import Faker
import random
 
app = Flask(__name__)
app.config.from_object(config)

db.init_app(app)


@app.cli.command()
def create():
    db.drop_all()
    db.create_all()
    print("create ok")
    
@app.cli.command("forge_module")
def forge_module():
    module = Module()
    modules = [
        {"module":"小组1"},
        {"module":"小组2"},
        {"module":"小组3"},
        {"module":"小组4"},
        {"module":"小组5"},   
    ]

    for m in modules:
        module = Module(module=m["module"])
        print(module)
        module.save()
        # db.session.add(module)
        # db.session.commit()  
    

@app.cli.command("forge_equipment")
def forge_equipment():
    fake = Faker(locale="zh-CN")
    for i in range(10):
        equipment = Equipment()
        profile = fake.simple_profile()  
        equipment.module = random.choice(['小组1', '小组2', '小组3'])
        if equipment.module == '小组1':
            equipment.name = random.choice(['A1','A2','A3'])
        elif equipment.module == '小组2':
            equipment.name = random.choice(['B1','B2'])
        elif equipment.module == '小组3':
            equipment.name = random.choice(['C1','C2','C3'])
        equipment.create_time = fake.date_between(start_date='-365d', end_date='today').strftime('%Y-%m-%d')  
        equipment.value = fake.random_int(min=300, max=400)
        equipment.save()


def alarm_to_dict(user):
    return OrderedDict(
        id = user.id,
        module = user.module,
        name = user.name,
        create_time = user.create_time,
        value = user.value,
    )





# 加载菜单
@app.route("/portal/initMenu")
def init_menu():
    rdata = dict()
    head = dict()
    head['title'] = "首页"
    head['href'] = "/welcome"
    rdata['homeInfo'] = head
    logos = dict()
    logos['title'] = "后台管理"
    logos['image'] = url_for("static", filename="images/logo.png")
    logos['href'] = ""
    rdata['logoInfo'] = logos
    # person_id = session['user_id']
    # permission = get_permission_list(person_id)  # 获取当前用户的权限列表
    rdata['menuInfo'] = get_function_menu()  # 根据权限获取功能菜单
    print(rdata)
    # return json.dumps(rdata, ensure_ascii=False)
    return jsonify(rdata)


# @app.route('/')
# def hello_world():
#     return "hello world!"



@app.route('/')
def menu():
    return render_template("menu.html") 


@app.route('/welcome')
def welcome():
    equipments = Equipment.query.all()
    return render_template('welcome.html',name='ALISA',chart_titles = ["设备","报警次数"],equipments=equipments) 



@app.route('/api')
def index():
    equipments = Equipment.query.all()
    return render_template("index.html",name='ALISA',chart_titles = ["设备","报警次数"],equipments=equipments) 



#搜索
@app.route('/api/equipment', methods=['GET'])
def equipment_view():
    page = request.args.get('page', type=int, default=1)
    per_page = request.args.get('limit', type=int, default=10)
    # q = db.select(Equipment)
    # q = Equipment.query.all()

    t = request.args.get('module',default="")
    name = request.args.get('equipment',default="")
    
    level = request.args.get('level',default="")
    start_date = request.args.get('start_date',default="")
    end_date = request.args.get('end_date',default="")

    
    if name:
        print("搜索name",name)
        q = Equipment.query.filter(Equipment.name.like(f'%{name}%'))
    elif t:
        print("搜索module",t)
        module_search = f"%{t}%"
        print("module_search",module_search)
        # q = Equipment.query.filter(Equipment.name.like(f'%{t}%')) 
        q = Equipment.query.filter(Equipment.module.like(module_search)) 
        print (q)
    elif level:
        print("搜索level",level)
        if level == "0":
            q = Equipment.query.filter(Equipment.value < 300)
        elif level == "1":
            q = Equipment.query.filter(Equipment.value >= 300)
    elif start_date:
        print("搜索start_date",start_date)
        if end_date and start_date:
            q = Equipment.query.filter(Equipment.create_time.between(start_date,end_date))
        else:
            q = Equipment.query.filter(Equipment.create_time >= start_date)
    else:
        q = Equipment.query

    print (q)
    
        
        
    paginate = q.paginate(page=page, per_page=per_page, error_out=False)
    # paginate = db.paginate(q, page=page, per_page=per_page, error_out=False)

    #items: [Equipment] = paginate.items
    # for item in items:
    #   print(item)
    return {
        'code': 0,
        'msg': '信息查询成功',
        'count': paginate.total,
        'data': [
            {
                'id': item.id,
                'module': item.module,
                'name': item.name,
                'create_time': item.create_time.strftime('%Y-%m-%d'),
                'value': item.value,
            } for item in paginate.items
        ]
    }



@app.route('/api/equipment/delete/<int:alarm_id>', methods=['POST'])  # 限定只接受 POST 请求
def delete(alarm_id):
    alarm = Equipment.query.get_or_404(alarm_id)  # 获取设备信息
    db.session.delete(alarm)  # 删除对应的记录
    db.session.commit()  # 提交数据库会话
    flash('Item deleted.')
    # return redirect(url_for('index'))  # 重定向回主页
    return {
        'code': 0,
        'message': '删除数据成功'
    }


@app.route('/api/equipment/batchdelete', methods=['POST'])  # 限定只接受 POST 请求
def batchdelete():
    data =request.form.get("ids")
    alarm_ids = eval(data)
    for alarm_id in alarm_ids:
        alarm = Equipment.query.get_or_404(alarm_id)  # 获取设备信息
        db.session.delete(alarm)  # 删除对应的记录
        db.session.commit()  # 提交数据库会话
        flash('BatchItem deleted.')
    return {
        'code': 0,
        'message': '删除数据成功'
    }



@app.route('/getalarmlist',methods=['GET'])
def getalarmlist():
    equipments = Equipment.query.all()
    equipment_data = list(map(alarm_to_dict, equipments))
    #print("equipment_data",equipment_data)

    #return jsonify(list(map(module_to_dict, modules)))
    # return jsonify({'code': 0,
    #                 'msg': '信息查询成功',
    #                 'data': equipmentdata})

    return jsonify({
            'code': 0,
            'msg': '信息查询成功',
            'data': equipment_data
        })


@app.route('/getequipmentlist',methods=['GET'])
def getequipmentist():
    equipments = Equipment.query.all()
    equipment_data = list(map(alarm_to_dict, equipments))
    #print("equipment_data",equipment_data)

    #return jsonify(list(map(module_to_dict, modules)))
    # return jsonify({'code': 0,
    #                 'msg': '信息查询成功',
    #                 'data': equipmentdata})

    return jsonify({
            'code': 0,
            'msg': '信息查询成功',
            'data': equipment_data
        })


@app.route('/api/equipment/add',methods=['GET', 'POST'])
def addalarm():
    modules = Module.query.all()
    equipments = Equipment.query.all()
    if request.method == 'POST':
        print("POST请求")
        data = request.get_json()
        print("data")
        print()
        data['create_time'] = datetime.datetime.strptime(data['create_time'], '%Y-%m-%d')
        print("日期",data['create_time'])

        #方式1
        stu = Equipment(**data)
        db.session.add(stu)

        #方式2
        # equipment = Equipment()
        # for key, value in data.items():
        #     setattr(equipment,key, value)
        # db.session.add(equipment) # 添加到数据库会话

        db.session.commit()  # 提交数据库会话
        return {
            'code': 0,
            'message': '新增成功'
        }

    return render_template("alarm-add.html",modules = modules,equipments = equipments)  #加入变量传递


@app.route('/api/equipment/edit/<int:alarm_id>',methods=['GET', 'POST'])
def editalarm(alarm_id):
    modules = Module.query.all()
    equipments = Equipment.query.all()
    if request.method == 'POST':
        print("alarmid",alarm_id)
        data = request.get_json()
        data['create_time'] = datetime.datetime.strptime(data['create_time'], '%Y-%m-%d')
        # print("日期",data['create_time'])
        # print("id是什么",data['id'])

        #alarm = Equipment.query.get_or_404(alarm_id)  # 获取设备信息

        #方式1
        # stu = Equipment(**data)
        # db.session.add(stu)

        #方式2
        alarm = Equipment.query.get_or_404(alarm_id)  # 获取设备信息
        for key, value in data.items():
            setattr(alarm,key,value)
        #db.session.update(alarm)


        db.session.commit()  # 提交数据库会话
        return {
            'code': 0,
            'message': '更新成功'
        }

    return render_template("alarm-edit.html",modules = modules,equipments = equipments)  #加入变量传递






if __name__ == '__main__':
    app.run()